package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import server.handler.EchoServerHandler;

import java.net.InetSocketAddress;

/**
 * 服务端
 *
 * @author wzg
 * @date 2021/6/18 22:20
 */
public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        //因为使用NIO，所以指定NioEventLoopGroup来接受和 处理新连接，指定通道类型为NioServerSocketChannel
        //创建NioEventLoopGroup对象来处理事件，如接受新连接、接收数据、写数据等等
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建一个ServerBootstrap对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //
            serverBootstrap.group(group).channel(NioServerSocketChannel.class)
                    //指定InetSocketAddress，服务器监听此端口
//                    .localAddress(port)
                    //设置ChannelHandler
                    //设置childHandler执行所有的连接请求
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline().addLast(new EchoServerHandler());
                        }
                    })
            .childOption(ChannelOption.AUTO_READ,true)
            .option(ChannelOption.SO_BACKLOG, 128)          // (5)
            .childOption(ChannelOption.SO_KEEPALIVE, true);
            //都设置完毕了，最后调用ServerBootstrap.bind() 方法来绑定服务器
            //调用sync()方法会阻塞直到服务器完成绑定
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println(EchoServer.class.getName() + "started and listen on " + channelFuture.channel().localAddress());
            //所以关闭操作也 会被阻塞。现在你可以关闭EventLoopGroup和释放所有资源，包括创建的线程。
            channelFuture.channel().closeFuture().sync();
        }  finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new EchoServer(65535).start();
    }
}
